﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace DoNetFrameworkWebApi.Models
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        DbSet<T> dbSet;
        private readonly AppDbContext context;

        public BaseRepository(AppDbContext context)
        {
            dbSet = context.Set<T>();
            this.context = context;
        }

        public void Delete(object id)
        {
            T target = Get(id);
            dbSet.Remove(target);
            context.SaveChangesAsync();
        }

        public IEnumerable<T> GetList()
        {
            return dbSet.ToArray();
        }

        public T Get(object id)
        {
            return dbSet.Find(id);
        }

        public void Insert(T entity)
        {
            dbSet.Add(entity);
            context.SaveChangesAsync();
        }

        public void Update(T entity)
        {
            dbSet.Attach(entity);
            context.Entry(entity).State = EntityState.Modified;
            context.SaveChangesAsync();
        }
    }
}